import {TriggerFactory} from "../frame/TriggerFactory";
import {PlayerModel} from "../frame/apiModel/adapterModel/model4/PlayerModel";
import {GuiControllerOpt, GuiId, TimeControllerOpt} from "../controller/model/ControllerOpt";
import {TimeController} from "../controller/TimeController";
import {PlayerDataKey} from "../frame/dataSource/DataSource";
import {ModelFactory} from "../frame/apiModel/adapterModel/model5/ModelFactory";
import {UnitModel} from "../frame/apiModel/adapterModel/model3/UnitModel";
import {CodeUtil} from "../frame/codeAdapter/CodeUtil";
import {PlayerFactory} from "../frame/PlayerFactory";
import {CastType1} from "../frame/dataSource/DataModel";
import {Logger} from "../frame/apiModel/config/Logger";
import {GuiController, OptType} from "../controller/GuiController";

export function selectedTrigger() {

    const fun = function (this: void, selectedPlayer: PlayerModel) {
        const callback = function () {
            const selectedUnits = ModelFactory.getInstance().getSelectedPlayer(selectedPlayer);
            const len = selectedUnits.length;

            const firstUnit = selectedUnits[0];
            const oldSelectUnit = selectedPlayer.data[PlayerDataKey.selectedUnit]

            if (len === 1) {
                const targetItem = selectedPlayer.data[PlayerDataKey.targetItem];
                const targetSpellInfo = selectedPlayer.data[PlayerDataKey.targetSpellInfo];
                let success = true;

                if (targetItem) {
                    const sellitems = firstUnit?.template?.Sellitems;
                    if (!CodeUtil.isNullOrZero(sellitems)) {
                        sellItemToUnit(selectedPlayer, oldSelectUnit);
                    } else {
                        giveItemToUnit(selectedPlayer, firstUnit);
                    }
                    success = false;
                } else if (targetSpellInfo.bShow) {
                    if (targetSpellInfo.type === CastType1.unit) {
                        useSpellToUnit(selectedPlayer, firstUnit, targetSpellInfo.id);
                        success = false;
                    }
                }

                if (success) {
                    GuiController.getInstance().showGui(new GuiControllerOpt(GuiId.buffBar, {}), selectedPlayer, OptType.open);
                    if (oldSelectUnit !== firstUnit) {
                        selectedPlayer.data[PlayerDataKey.selectedUnit] = firstUnit;
                        const newOwner = PlayerFactory.getInstance().getUnitOwner(firstUnit);
                        // Logger.toastError(`${selectedPlayer?.name} 选择了 ${firstUnit?.name} ${firstUnit?.id}`);
                        if (newOwner && newOwner.playerId === selectedPlayer.playerId) {
                            // Logger.toastError(`${newOwner?.name} 设置了 ${firstUnit?.name} 为主单位`);
                            selectedPlayer.data[PlayerDataKey.lastOwnerSelectedUnit] = firstUnit;
                        }
                    }
                }
            } else {
                GuiController.getInstance().showGui(new GuiControllerOpt(GuiId.buffBar, {}), selectedPlayer, OptType.close);
                // firstUnit.select(true)
            }
            // selectedPlayer.clearSelecteds();
        }
        const opt: TimeControllerOpt = new TimeControllerOpt(undefined, callback, 1);
        TimeController.getInstance().startTimer({ opt, time: 0.01 });
    }


    TriggerFactory.getInstance().registerPlayerSelected(fun);
}

function giveItemToUnit (player: PlayerModel, selectUnit: UnitModel) {
    const targetItem = player.data[PlayerDataKey.targetItem];
    if (targetItem?.isValid()) {
        if (selectUnit?.isValid()) {
            ModelFactory.getInstance().unitAddItem(selectUnit, targetItem);
            player.data[PlayerDataKey.targetItem] = undefined
        }
    }
}

function sellItemToUnit (player: PlayerModel, selectUnit: UnitModel) {
    const targetItem = player.data[PlayerDataKey.targetItem];
    if (targetItem) {
        if (selectUnit?.isValid()) {
            ModelFactory.getInstance().sellItem(selectUnit, targetItem);
        }
    }
}

function useSpellToUnit (player: PlayerModel, selectUnit: UnitModel, id: string) {
    const selectedUnit = player.data[PlayerDataKey.selectedUnit];
    if (selectedUnit?.isValid()) {
        const ret = selectedUnit.useAbility(id, selectUnit.loc, selectUnit);
        if (ret) {
            player.hideAbilityEffect()
        } else {
            Logger.toastError(`${selectedUnit.name} 施放 ${id} 失败, 可能是技能允许目标设置不正确`);
        }
    }
}